package com.shop.user.controller;

import com.base.common.entity.User;
import com.base.common.http.HttpResult;
import com.base.common.utils.Md5Salt;
import com.base.common.utils.UserUtils;
import com.shop.user.from.RegisterUserFrom;
//import com.shop.user.http.HttpResult;
import com.shop.user.service.UserService;
//import com.shop.user.entity.User;
//import com.shop.user.utils.Md5Salt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

/**
 * @ClassName UserController
 **/
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/verifyCode")
    public HttpResult verifyCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
        Boolean result = userService.verifyCode(phone, code);
        return HttpResult.ok(result);
    }


    @RequestMapping("/sendCode")
    public HttpResult sendCode(@RequestParam("phone") String phone) {
        try {
            userService.sendCode(phone);
            return HttpResult.ok("发送验证码成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpResult.ok("发送验证码失败!");
    }

    @RequestMapping("/getUserInfo")
    public HttpResult getUserInfo(HttpServletRequest request) {
        User user = UserUtils.getUser(request);
        HttpResult result = HttpResult.ok(user);
        return result;
    }

    @RequestMapping("/add")
    public HttpResult add(@Valid RegisterUserFrom from){
        User user = new User();
        BeanUtils.copyProperties(from, user);
        Date date = new Date();
        user.setPassword(Md5Salt.getMD5(from.getPassword()));
        user.setCreated(date);
        user.setUpdated(date);
        user.setLocation("收货地址。。。");
        System.out.println(user.toString());
        try {
            Boolean isCodeTrue = userService.verifyCode(from.getPhone(), from.getCode());
            if (!isCodeTrue) {
                return HttpResult.error("验证码错误!");
            }
            userService.add(user);
            return HttpResult.ok("添加用户成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpResult.error("添加用户失败!");
    }

    @RequestMapping("/updateUserInfo")
    public HttpResult updateUserInfo(String headUrl, HttpServletRequest request) {
        User user = UserUtils.getUser(request);
        user.setHeadPic(headUrl);
        boolean bool = userService.updateUserInfo(user);
        if (bool ==true) {
            return HttpResult.ok();
        }
        return HttpResult.error();
    }

}
